package com.rslai.base.tool.servertest;

import com.rslai.base.tool.servertest.model.CaseStatistics;
import com.rslai.base.tool.servertest.model.KeyValueStore;
import com.rslai.base.tool.servertest.transport.http.HttpService;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Statistics {
    private static final Logger logger = LoggerFactory.getLogger(Statistics.class);

    public static void start(CaseStatistics caseStatistics) {
        try {
            if (!isValid(caseStatistics)) return;
            HttpService.entityRequest("http://autotest.corp.qunar.com/api/set/statistics.do", "POST", buildParameters(caseStatistics));
        } catch (Exception e) {
            logger.error("Start set memcached error", e);
        }
    }

    private static List<KeyValueStore> buildParameters(CaseStatistics caseStatistics) {
        KeyValueStore job = new KeyValueStore("job", caseStatistics.getJob());
        KeyValueStore build = new KeyValueStore("build", caseStatistics.getBuild());
        KeyValueStore runNum = new KeyValueStore("runNum", String.valueOf(caseStatistics.getRunSum()));
        KeyValueStore successedNum = new KeyValueStore("successedNum", String.valueOf(caseStatistics.getSuccess()));
        KeyValueStore failedNum = new KeyValueStore("failedNum", String.valueOf(caseStatistics.getFailed()));
        KeyValueStore caseDescs = new KeyValueStore("caseDescs", caseStatistics.getFailedIdList());
        return Arrays.asList(new KeyValueStore[]{job, build, runNum, failedNum, successedNum, caseDescs});
    }

    private static boolean isValid(CaseStatistics caseStatistics) {
        if ((StringUtils.isBlank(caseStatistics.getJob())) || (StringUtils.isBlank(caseStatistics.getBuild()))) {
            return false;
        }
        return true;
    }
}
